import Vue from 'vue'
import VueRouter from 'vue-router'

Vue.use(VueRouter)

// 路由懒加载方式
const Home = () => import('@/views/home')
import store from '@/store'
const Login = () => import('@/views/login')
const Question = () => import('@/views/question')
const Video = () => import('@/views/video')
const User = () => import('@/views/user')
const Profile = () => import('@/views/user/profile')
const Chat = () => import('@/views/user/chat')
const Article = () => import('@/views/article')
const Tabbar = () => import('@/components/app-tabbar.vue')

const routes = [
  {
    path: '/login',
    component: Login
  },
  {
    path: '/',
    alias: 'Home',
    components: {
      default: Home,
      bottom: Tabbar
    }
  },
  {
    path: '/question',
    components: {
      default: Question,
      bottom: Tabbar
    }
  },
  {
    path: '/video',
    components: {
      default: Video,
      bottom: Tabbar
    }
  },
  {
    path: '/user',
    components: {
      default: User,
      bottom: Tabbar
    }
  },
  {
    path: '/article/:id',
    components: {
      default: Article
    }
  },
  // {
  //   path: '/article',
  //   components: {
  //     default: Article
  //   }
  // },
  {
    path: '/user/profile',
    component: Profile
  },
  {
    path: '/user/chat',
    component: Chat
  }
]

const router = new VueRouter({
  routes
})
//导航守卫 需要登录才可以访问的页面
const whitPath = ['/user', '/user/profile', '/user/chat']
router.beforeEach((to, form, next) => {
  if (store.getters['user/getToken']) {
    if (to.path.toLowerCase() === '/login') {
      next('/')
    } else {
      next()
    }
  } else {
    // if (to.path.toLowerCase().startsWith('/user')) {
    if (whitPath.includes(to.path.toLowerCase())) {
      next('/login?redirect=' + to.fullPath)
    } else {
      next()
    }
  }
  const routerPush = VueRouter.prototype.push
  VueRouter.prototype.push = function push (location) {
    return routerPush.call(this, location).catch(error => error)
  }
})

export default router
